var policeNo;
var MapIndex = {
	overlay:{
		areaOverlay:[],
		userOverlay:[],
		chuzuwuOverlay:[],
		policeMarker:null,
		policeLineMarker:new BMap.Polyline([], {strokeColor:"blue", strokeWeight:3, strokeOpacity:0.5})
	},
	isApp:0,
	showTimeIntervalId:null,
	map:null,
	infoWindows:null,
	init:function(){
		 var me =this;
		 policeNo = sbl.getParameter("no");
		 var app = sbl.getParameter("app");
		 boss.isApp = app;
		 
		 me.switchTopPabel(true);
		 me.switchRightPabel(false);
		 me.initLayout();
		 me.initBaseMap();
		 me.reloadMapOverlay();		 
		 me.initAreaLayer();
		 me.initEvent();
		 me.initPolicePositionLayer();
	},
	initLayout:function(){
		$("div[under], div[tag='z2'], div[tag='z3'], div[tag='z4']").hide();
	},
	initEvent:function(){
		var boss = this;
		
		$(".menuTitle").bind("click",function(){
			var ul = $(this).next("ul");
			if(ul.is(":hidden")){
				$(".menuList").hide(300);
				ul.show("300");
			}
			else{
				ul.hide("300");
			}
		});
		
		$(".menuList li").bind("click",function(){
			$(".menuList li").removeClass("selected");
			$(".menuList").removeAttr("selected");
			if($(this).hasClass("selected")){
				$(this).removeClass("selected");
			}
			else{
				$(this).addClass("selected");
			}
			
			$(".menuList li.selected").parent().attr("selected","selected");
			boss.reloadMapOverlay(true);
		});
		
		$(".menuTitle .selectAll").bind("click",function(event){
			
			var selectAll = $(this).attr("selectAll");
			var ul = $(this).parent("p").parent("div").children(".menuList");
			$(".menuList").removeAttr("selected");
			$(".menuList li").removeClass("selected");
			if(!selectAll){
				ul.attr("selected","selected");
				ul.children("li").addClass("selected");
				$(this).html("取消");
				$(this).attr("selectAll","selectAll");
			}
			else{
				ul.removeAttr("selected");
				ul.children("li").removeClass("selected");
				$(this).html("全选");
				$(this).removeAttr("selectAll","selectAll");
			}
			event.stopPropagation();
			boss.reloadMapOverlay(true);
		});
		
		$("#panel_switch").bind("click",function(){
			if($(this).hasClass("panel_open")){
				$(this).removeClass("panel_open");
				$(this).addClass("panel_close");
				boss.switchRightPabel(true);
			}
			else{
				$(this).removeClass("panel_class");
				$(this).addClass("panel_open");
				boss.switchRightPabel(false);
			}
		});
		
		$("#shouqi").bind("click",function(){
			if($(this).attr("close")){
				$(this).removeAttr("close");
				$(this).html("全屏");
				boss.switchTopPabel(true);
				boss.switchRightPabel(true);
			}
			else{
				$(this).attr("close","close");
				$(this).html("返回");
				boss.switchTopPabel(false);
				boss.switchRightPabel(false);
			}
		});
		
		$("#tab li").bind("click", function(){
			var tab = $(this).attr("tag");
			window.location.href = burl + "/main.jsp?tab=" + tab;
		});
		
		$(".map_list_title").bind("click",function(){
			var dw = $(this).attr("dw");
			var ul = $("#list_div_context ul[dw='"+dw+"']");
			if(ul.is(":hidden")){
				ul.show(300);
			}
			else{
				ul.hide(300);
			}
		});
		
		$("#listDivSwitch").bind("click",function(){
			if($("#map_list_table_div").is(":hidden")){
				$("#map_list_table_div").show();
				$("#listDivSwitch").html("关闭列表");
			}
			else{
				$("#map_list_table_div").hide();
				$("#listDivSwitch").html("打开列表");
			}
		});
		
		$("#map_list_sendorder_btn").bind("click",function(){
			prompt("请输入指令","");
		});
		
		orgSelecter.initOrgSelecter(function(){
			boss.reloadMapOverlay();
			boss.initAreaLayer();
			var mapx = $("#xuanxiangka div[tag^='z'][selected]").last().attr("mapx");
			var mapy = $("#xuanxiangka div[tag^='z'][selected]").last().attr("mapy");
			var zoom = parseInt($("#xuanxiangka div[tag^='z'][selected]").last().attr("zoom"));
			if(mapx > 1){
				var center = new BMap.Point(mapx,mapy);
				boss.map.centerAndZoom(center, zoom);
			}
			
		},boss);
	},
	initBaseMap:function(zoom){
		var boss = this;
        if(!zoom){
        	zoom = 15;
        }
		boss.map = new BMap.Map("mapDiv");    
		boss.map.centerAndZoom(new BMap.Point(113.895367, 22.56343), zoom);
		boss.map.addControl(new BMap.MapTypeControl());
		boss.map.enableScrollWheelZoom();
		
		var myZoomCtrl = new MyMapControl(BMAP_ANCHOR_TOP_RIGHT,20, 40,"<div class='quanping' id='shouqi'>全屏</div>");
		boss.map.addControl(myZoomCtrl);
		var gpsReloadTip = new MyMapControl(BMAP_ANCHOR_TOP_RIGHT,20, 40,"<div class='gpsReloadTip' second='6' id='gpsReloadTip'>5秒后更新……</div>");
		boss.map.addControl(gpsReloadTip);
		var listDivSwitch = new MyMapControl(BMAP_ANCHOR_TOP_RIGHT,20, 40,"<div id='listDivSwitch'>打开列表</div>");
		boss.map.addControl(listDivSwitch);
		var mapListDiv = new MyMapControl(BMAP_ANCHOR_TOP_RIGHT,20, 40,"<div id='map_list_table_div'></div>");
		boss.map.addControl(mapListDiv);
		$("#shouqi,#map_list_table_div,#listDivSwitch,#gpsReloadTip").removeAttr("style");
		$("#map_list_table_div").html($("#temcontent").html());
		$("#map_list_table_div").hide();
		$("#temcontent").remove();
		$("#map_list_table_div").css("width","400px");
		
		boss.map.addEventListener("zoomend", boss.reloadMapOverlay);
		boss.map.boss = boss;
	},
	initAreaLayer:function(){
		var boss = this;
		var zoom = boss.map.getZoom();
		boss.clearAreaOverlay();
		boss.overlay.areaOverlay = [];
		
		var fullid = $("#xuanxiangka div[tag^='z'][selected]").last().attr("fullid");
		var zoomLevel = boss.getZoomLevel();
		if(zoomLevel == "baoan"){
			//宝安分局
			boss.loadAreaLayer("0-1-","2",fullid,null,"red");
		}
		else if(zoomLevel == "paichusuo"){
			//派出所
			boss.loadAreaLayer("0-1-","3",fullid,null,"red");
		}
		else if(zoomLevel == "jingqu"){
			//派出所和警区
			boss.loadAreaLayer(orgSelecter.getPaichusuoFullid(),"4",fullid,null,"blue");
		}
		else if(zoomLevel == "zerenqu"){
			//派出所和责任区
			boss.loadAreaLayer(orgSelecter.getPaichusuoFullid(),"5",fullid,null,"blue");
		}
	},
	initPolicePositionLayer:function(){
		var boss = this;
		var row = modelDao.getPoliceModel(policeNo);
		boss.clearMapOverLay();
		userOverlay = {};
		var mtUser = ['李远松','黄宝','潘宗春','梁高培','王涛','吴飞','李哲','胡小伟','张克龙','颜醒宇','窦传伟','洪钟群'];
			var point = new BMap.Point(row.x,row.y);
			var dwType = "";
			if(row.personproperty=="治安员"){
				dwType = "1";
			}
			else if(row.personproperty=="巡防员"){
				dwType = "2";
			}
			else if(row.personproperty=="保安"){
				dwType = "3";
			}
			var icon = new BMap.Icon(burl+"/images/map/team/"+dwType+".png", new BMap.Size(32,56));
			for(var ii =0;ii<mtUser.length;ii++){
				var userName = mtUser[ii];
				if(userName == row.name){
					icon = new BMap.Icon(burl+"/images/map/mt.png", new BMap.Size(70,53));
					break;
				}
			}
			var Marker = new BMap.Marker(point);
			Marker.data = row;						
			Marker.addEventListener("click",function(){
				this.map.boss.showPoliceInfoWindows(this);								
			});
			Marker.setZIndex(9999);
			Marker.setIcon(icon);
			boss.overlay.policeMarker=Marker;
			boss.map.addOverlay(Marker);
			boss.map.addOverlay(boss.overlay.policeLineMarker);
		setInterval(boss.reloadPosition,5000);
		boss.showTimeIntervalId = setInterval(boss.showGpsReloadTime,1000);
	},
	reloadPosition:function(){
		var boss = MapIndex;
		var oldMarket = boss.overlay.policeMarker;
		var oldPoint = new BMap.Point(oldMarket.getPosition().lng, oldMarket.getPosition().lat);
		
		var row;
		if(boss.isApp == "1"){
			row = modelDao.getUserPositionModel(policeNo);
		}
		else{
			row = modelDao.getPoliceModel(policeNo);
		}
		
		$("#gpsReloadTip").attr("second",6);
		$("#gpsReloadTip").html("5秒后刷新……");
		boss.showTimeIntervalId = setInterval(boss.showGpsReloadTime,1000);
		clearInterval(boss.showTimeIntervalId);
		var point = new BMap.Point(row.x,row.y);
		var map = boss.map;
		boss.overlay.policeMarker.setPosition(point);
		
		if(!map.getBounds().containsPoint(point))
		{
			map.setCenter(point);
		}
		
		var gpsTime = boss.overlay.policeMarker.data.gpsTime;
		if(row.gpsTime == gpsTime){
			oldMarket.data = row;
			return;
		}
		
		var gpsPointMarker = new BMap.Marker(oldPoint);
		var icon = new BMap.Icon(burl+"/images/map/point.png", new BMap.Size(10,10));
		gpsPointMarker.setIcon(icon);
		gpsPointMarker.setShadow(new BMap.Icon(burl+"/images/map/sd.png", new BMap.Size(10,10)));
		gpsPointMarker.addEventListener("click",function(){
			this.map.boss.showPoliceInfoWindows(this);								
		});
		gpsPointMarker.data = oldMarket.data;
		boss.map.addOverlay(gpsPointMarker);
		oldMarket.data = row;
		boss.addPositionToList(row);
		var points = boss.overlay.policeLineMarker.getPath();
		points.push(oldPoint);
      		
		    points.push(point);
		
		boss.overlay.policeLineMarker.setPath(points);
	},
	addPositionToList:function(data){
		var tr = $("<tr></tr>");
		tr.append("<td style='width:130px'>"+data.gpsTime.split(" ")[1]+"</td>");
		tr.append("<td style='width:80px'>"+(data.x+"").substr(0,10)+"</td>");
		tr.append("<td style='width:80px'>"+(data.y+"").substr(0,9)+"</td>");
		tr.append("<td style='width:80px'>"+data.speed+"</td>");
		$("#positionTable").append(tr);
	},
	showPoliceInfoWindows:function(overlay){
		var boss = overlay.map.boss;
		var point = new BMap.Point(overlay.getPosition().lng, overlay.getPosition().lat);
		var model = overlay.data;
		var htmlContent = "<table style='width:350px'>";
		htmlContent += "<tr>";
		htmlContent += "<td style='width: 50px;'>姓名：</td><td>"+model.name+"</td>";
		htmlContent += "</tr>";
		htmlContent += "<tr>";
		htmlContent += "<td>单位：</td><td>"+model.unitName+"</td>";
		htmlContent += "</tr>";
		htmlContent += "<tr>";
		htmlContent += "<td>警号：</td><td>"+model.policeNo+"</td>";
		htmlContent += "</tr>";
		htmlContent += "<tr>";
		htmlContent += "<td>时间：</td><td>"+model.gpsTime+"</td>";
		htmlContent += "</tr>";
		htmlContent += "<tr>";
		htmlContent += "<td>位置：</td><td style='width:250px' id='historyAddressTd'>地址解析中……</td>";
		htmlContent += "</tr>";
		htmlContent += "<tr>";
		htmlContent += "<td></td><td><button no='"+overlay.data.no+"' y='"+overlay.getPosition().lat+"' x='"+overlay.getPosition().lng+"' id='zl_btn'>发送指令</button></td>";
		htmlContent += "</tr><table>";
		var infoWindows = new BMap.InfoWindow(htmlContent);
		infoWindows.addEventListener("open",function(){
			$("#zl_btn").bind("click",function(){
				var x = $(this).attr("x");
				var y = $(this).attr("y");
				var no = $(this).attr("no");
				boss.showOrderWindows(x,y,no);
			});
		});
			
		boss.map.openInfoWindow(infoWindows,point);
		boss.loadAddress(overlay.getPosition().lng, overlay.getPosition().lat,"historyAddressTd");
	},
	showOrderWindows:function(x,y,no){
		var boss = this;
		var point =new BMap.Point(x,y);
		var model = modelDao.getPoliceModel(no);
		var htmlContent = "<form id='orderForm'><table>";
		htmlContent += "<tr>";
		htmlContent += "<td>姓名：</td><td>"+model.name+"</td>";
		htmlContent += "</tr>";
		htmlContent += "<tr>";
		htmlContent += "<td>单位：</td><td>"+model.unitName+"</td>";
		htmlContent += "</tr>";
		htmlContent += "<tr>";
		htmlContent += "<td>警号：</td><td>"+model.policeNo+"</td>";
		htmlContent += "</tr>";
		htmlContent += "<tr>";
		htmlContent += "<td>发送内容：</td><td><input name='title' /></td>";
		htmlContent += "</tr>";
		htmlContent += "<tr>";
		htmlContent += "<td>发送图片：</td><td><input type='file' name='img'/></td>";
		htmlContent += "</tr>";
		htmlContent += "<tr>";
		htmlContent += "<td colspan='2'><button id='fs_btn'>发送</button></td>";
		htmlContent += "</tr>";
		htmlContent += "</table>";
		htmlContent += "</form>";
		var infoWindows = new BMap.InfoWindow(htmlContent); 
		
		infoWindows.addEventListener("open",function(){
			$("#fs_btn").bind("click",function(){
				$("#fs_btn").html("发送中…");
				sbl.submit({
					data:'orderForm',
					url:burl+"/Todo/add.do",
					success:function(dd){
						alert("发送成功");
						infoWindows.close();
					}
				});
			});
		});
		boss.map.openInfoWindow(infoWindows,point);
	},
	showGpsReloadTime:function(){
		var second = $("#gpsReloadTip").attr("second");
	 	second = parseInt(second);	
	 	if(!second||second=='1')
	 	{
	 		return;
	 	}
	 	second = second - 1;
		$("#gpsReloadTip").attr("second",second);
		$("#gpsReloadTip").html(second+"秒后刷新");
	},
	clearMapOverLay:function(){
		var boss = this;
		
		if(boss.markerClustererLayer){
			MapIndex.markerClustererLayer.removeMarkers(boss.overlay.chuzuwuOverlay);
			MapIndex.markerClustererLayer.clearMarkers();
		}
		
		for(var key in boss.overlay.userOverlay){
			boss.map.removeOverlay( boss.overlay.userOverlay[key]);
		}
		
		for(var i=0;i<boss.overlay.chuzuwuOverlay.length;i++){
			boss.map.removeOverlay(boss.overlay.chuzuwuOverlay[i]);
		}
	},
	clearAreaOverlay:function(){
		var boss = this;
		
		for(var i in boss.overlay.areaOverlay){
			boss.map.removeOverlay(boss.overlay.areaOverlay[i]);
		}
	},
	loadAreaLayer:function(fullid,requeslevel,currentFullid,colorAttr,strokeColor){
		var boss = this;
		var bound = boss.map.getBounds();
		var miny = bound._swLat;
		var minx = bound._swLng;
		var maxy = bound._neLat;
		var maxx = bound._neLng;
		var url = "";
		
		sbl.ajax({
			dataType:'json',
			type:'get',
			data:{miny:miny,minx:minx,maxy:maxy,maxx:maxx,fullid:fullid,level:requeslevel},
			url:burl+"/Dept/getOrgByLevel.do",
			success:function(dd){
				var data;
				if(!dd.length){
					data = [dd];
				}
				else{
					data = dd;
				}
				var parentFullid = boss.getParentFullid(currentFullid);
				var selectedOrgLevel = boss.zoomLevelMapper[boss.getFullidLevel(currentFullid)];
				for(var i=0;i<data.length;i++){
					var d = data[i];
					var colorIndex = parseInt(d.fullid[d.fullid.length-2]);
					var points = [];
					var lonlats = d.mapxy.split(";");
					
					for(var j =0;j<lonlats.length;j++){
						var lonlat = lonlats[j].split(",");
						var lon = lonlat[0];
						var lat = lonlat[1];
						var point = new BMap.Point(lon,lat);
						points.push(point);
					}
					var fillColor = "gray";
					if(selectedOrgLevel > requeslevel){
						if(parentFullid.indexOf(d.fullid) > -1){
							fillColor = "";
						}
					}
					else if(selectedOrgLevel == requeslevel){
						if(d.fullid == currentFullid){
							fillColor = "";
						}
					}
					else if(selectedOrgLevel < requeslevel){
						if(d.fullid.indexOf(currentFullid)>-1){
							fillColor = "";
						}
					}
					
					var option={fillColor:fillColor,strokeWidth:"5px",fillOpacity:0.4,strokeStyle:"dashed",strokeColor:strokeColor};
					var polygon = new BMap.Polygon(points,option);
					boss.map.addOverlay(polygon);
					polygon.setStrokeWeight(4);
					boss.overlay.areaOverlay.push(polygon);
				}
			}
		});
	},
	loadAddress:function(x,y,domid){
		
		var gc = new BMap.Geocoder(); 
		var point = new BMap.Point(x,y);
		
		 gc.getLocation(point, function(rs){				 	
	        var address = rs.address;
	        $("#"+domid).html(address);
		 });     
	},
	reloadMapOverlay:function(force){
		var boss = this.boss;
		if(!boss){
			boss = this;
		}
		var zoom = boss.map.getZoom();
		var selectMenu = $(".menuList[selected]").attr("tag");
		if(!boss){
			boss = this;
		}
		boss.map.closeInfoWindow();
		boss.clearMapOverLay();
		$("#listDivSwitch").hide();
		$("#listDivSwitch").html("打开列表");
		$("#map_list_table_div").hide();
		$("#listDivSwitch").show();
	},
	switchRightPabel:function(isOpen){
		var pabelWidth = 212;
		var bodyWidth = document.documentElement.clientWidth;
		var mainWidth = 0;
		
		if(isOpen){
			mainWidth = bodyWidth - pabelWidth - 2;
			$("#filter").show();
		}
		else{
			mainWidth = bodyWidth;
			$("#filter").hide();
		}
		
		$(".main").css("width", mainWidth);
		$(".container").css("width",bodyWidth);
	},
	switchTopPabel:function(isOpen){
		var pabelHeight = 110;
		var bodyHeight = document.documentElement.clientHeight;
		var mainHeight = 0;
		
		if(isOpen){
			mainHeight = bodyHeight - pabelHeight;
			$(".header").show();
		}
		else{
			mainHeight = bodyHeight;
			$(".header").hide();
		}
		
		$(".main,#filter").css("height", mainHeight);
	},
	getZoomLevel:function(){
		var boss = this;
		var zoom = boss.map.getZoom();
		
		if(zoom <= 14){
			return "baoan";
		}
		else if(zoom == 15){
			return "paichusuo";
		}
		else if(zoom == 16){
			return "jingqu";
		}
		else {
			return "zerenqu";
		}
	},
	zoomLevelMapper:{
		baoan:2,
		paichusuo:3,
		jingqu:4,
		zerenqu:5
	},
	getParentFullid:function(fullid){
		var fullids = fullid.split("-");
		var result = "";
		
		if(fullids.length > 3){
			for(var i=0;i<fullids.length-2;i++){
				result += fullids[i]+"-"
			}
		}
		return result;
	},
	getFullidLevel:function(fullid){
		var infos = fullid.split("-");
		if(infos.length == 3){
			return "baoan";
		}
		else if(infos.length == 4){
			return "paichusuo";
		}
		else if(infos.length == 5){
			return "jingqu";
		}
		else if(infos.length == 6){
			return "zerenqu";
		}
	}
};
$(function(){
	MapIndex.init();
});